package org.dim.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.dim.oa.mapper.FileMapper;
import org.dim.oa.po.FileEntity;
import org.dim.oa.po.ServerResponse;
import org.dim.oa.utils.FileUtil;
import org.dim.oa.utils.Snowflake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * Created by lmj on 2021/3/19.
 */
@RestController
@Slf4j
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Value("${file.bucket}")
    private String bucket;

    @Autowired
    FileMapper fileMapper;

    @SneakyThrows
    @PostMapping("/upload")
    public ServerResponse upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ServerResponse.fail(400, "上传失败，请选择文件");
        }
        FileUtil.mkdirs(bucket);
        Long fileId = Snowflake.getInstance().get();
        File dest = new File(bucket +"/"+ fileId);
        file.transferTo(dest);
        byte[] decode = Base64.getDecoder().decode(request.getHeader("file_path"));
        String s = new String(decode);
        String accessFlag = request.getHeader("access_flag");
        Integer accessFlagRes=StringUtils.isEmpty(accessFlag)==true?1:Integer.parseInt(accessFlag);
        FileEntity fileEntity = FileEntity.builder().id(fileId).originalFileName(file.getOriginalFilename())
                .accessFlag(accessFlagRes)
                .dir(0)
                .fileType(FileUtil.getFileType(file.getOriginalFilename()))
                .bucket(bucket).fileName(String.valueOf(fileId)).filePath(s)
                .creator("-1").build();
        int insert = fileMapper.insert(fileEntity);
        if (insert == 1) {
            return ServerResponse.success(fileEntity);
        } else {
            return ServerResponse.fail(500, "保存失败");
        }
    }

    @SneakyThrows
    @GetMapping("/download/{fileId}")
    public void upload(HttpServletResponse response,@PathVariable(name = "fileId") String fileId) {
        QueryWrapper<FileEntity> fileEntityQueryWrapper = new QueryWrapper<>();
        FileEntity dbFileEntity = fileMapper.selectOne(fileEntityQueryWrapper.eq("id", Long.parseLong(fileId)));
        String s = bucket + "/" + dbFileEntity.getId();
        byte[] bytes = FileUtil.getBytes(s);
        response.addHeader("Accept-Ranges", "bytes");
        response.setStatus(200);
        response.setContentType("application/octet-stream");
        response.addHeader("Content-disposition", "attachment;filename="
                + new String(dbFileEntity.getOriginalFileName().getBytes("UTF-8"), "ISO-8859-1"));
        response.getOutputStream().write(bytes);
    }
    @SneakyThrows
    @PostMapping("/list")
    public ServerResponse list(@RequestBody FileEntity fileEntity) {
        QueryWrapper<FileEntity> queryWrapper = new QueryWrapper<>();
        /**
         * queryWrapper.like有三个参数
         * 第一个参数：该参数是一个布尔类型，只有该参数是true时，才将like条件拼接到sql中；本例中，如果name字段不为空，则拼接name字段的like查询条件；
         第二个参数：该参数是数据库中的字段名；
         第三个参数：该参数值字段值；
         这里的like查询是使用的默认方式，也就是说在查询条件的左右两边都有%：NAME = ‘%王%’；
         如果只需要在左边或者右边拼接%，可以使用likeLeft或者likeRight方法。
         */
        queryWrapper.likeRight(!StringUtils.isEmpty(fileEntity.getFilePath()),
                "file_path", fileEntity.getFilePath());
        List<FileEntity> fileEntities = fileMapper.selectList(queryWrapper);
        Set<FileEntity> strSet = new HashSet<>();
        Set<String> uniCurPath = new HashSet<>();
        String parameter=fileEntity.getFilePath();
        for (FileEntity obj:fileEntities) {
                if (obj.getFilePath().equals(parameter) && obj.getDir() == 1) {
                    continue;
                }
                if (obj.getDir() == 1) {
                    //是目录
                    String name = obj.getFilePath();
                    String[] split = name.split("/");
                    String s="";
                    if (parameter.equals("/")){
                        s= split[1];
                    }else {
                      //  paramter="/a/b"------["",a,b]  长度为3
                      //  paramter="/"------[]  长度为0
                        s=split[parameter.split("/").length];
                    }
                    obj.setCurPath(s);
                    //uniCurPath.add(s);
                    if (uniCurPath.contains(s)){

                    }else {
                        uniCurPath.add(s);
                        strSet.add(obj);
                    }

                } else {
                    //是文件
                    if (obj.getFilePath().equals(parameter)) {
                        obj.setCurPath(obj.getOriginalFileName());
                        if (uniCurPath.contains(obj.getOriginalFileName())){

                        }else {
                            uniCurPath.add(obj.getOriginalFileName());
                            strSet.add(obj);
                        }
                    }
                }

        }
        return ServerResponse.success(strSet);
    }
    
    
    @RequestMapping("/addFloader")
    public ServerResponse addFloader(String floaderName){
        Long id = Snowflake.getInstance().get();
        FileEntity build = FileEntity.builder().filePath(floaderName)
                .fileName(String.valueOf(id)).originalFileName(String.valueOf(id)).fileType("文件夹")
                .dir(1).creator("-1").filePath(floaderName).createTime(new Date()).id(id).build();
        fileMapper.insert(build);
        return ServerResponse.success();
    }

    @SneakyThrows
    @GetMapping("/delete/{fileId}")
    public ServerResponse delete(@PathVariable(name = "fileId") String fileId) {
        QueryWrapper<FileEntity> fileEntityQueryWrapper = new QueryWrapper<>();
        int res = fileMapper.delete(fileEntityQueryWrapper.eq("id", Long.parseLong(fileId)));
       return ServerResponse.success(res);
    }
}
